package com.xiaoxu.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoxu.base.exception.bkSchoolException;
import com.xiaoxu.base.model.PageParams;
import com.xiaoxu.base.model.PageResult;
import com.xiaoxu.content.dao.CourseBaseMapper;
import com.xiaoxu.content.dao.CourseCategoryMapper;
import com.xiaoxu.content.dao.CourseMarketMapper;
import com.xiaoxu.content.model.dto.AddCourseDto;
import com.xiaoxu.content.model.dto.CourseBaseInfoDto;
import com.xiaoxu.content.model.dto.EditCourseDto;
import com.xiaoxu.content.model.dto.QueryCourseParamsDto;
import com.xiaoxu.content.model.po.CourseBase;
import com.xiaoxu.content.model.po.CourseCategory;
import com.xiaoxu.content.model.po.CourseMarket;
import com.xiaoxu.content.service.CourseBaseService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 课程基本信息 服务实现类
 *
 * @author xiaoxu
 */
@Slf4j
@Service
public class CourseBaseServiceImpl extends ServiceImpl<CourseBaseMapper, CourseBase> implements CourseBaseService {

    private final CourseBaseMapper courseBaseMapper;
    private final CourseMarketMapper courseMarketMapper;

    private final CourseCategoryMapper courseCategoryMapper;

    public CourseBaseServiceImpl(CourseBaseMapper courseBaseMapper, CourseMarketMapper courseMarketMapper, CourseCategoryMapper courseCategoryMapper) {
        this.courseBaseMapper = courseBaseMapper;
        this.courseMarketMapper = courseMarketMapper;
        this.courseCategoryMapper = courseCategoryMapper;
    }

    /**
     * 查询数据库中课程的分页信息
     * @param pageParams 分页参数
     * @param queryCourseParams  查询条件
     * @return PageResult<CourseBase>
     */
    @Override
    public PageResult<CourseBase> queryCourseList(PageParams pageParams, QueryCourseParamsDto queryCourseParams) {
        LambdaQueryWrapper<CourseBase> courseBaseQueryWrapper = new LambdaQueryWrapper<>();
        //封装查询条件
        courseBaseQueryWrapper.like(StringUtils.isNotBlank(queryCourseParams.getCourseName()), CourseBase::getName, queryCourseParams.getCourseName());
        courseBaseQueryWrapper.eq(StringUtils.isNotEmpty(queryCourseParams.getAuditStatus()), CourseBase::getAuditStatus, queryCourseParams.getAuditStatus());
        courseBaseQueryWrapper.eq(StringUtils.isNotEmpty(queryCourseParams.getPublishStatus()), CourseBase::getStatus, queryCourseParams.getPublishStatus());
        //封装分页查询条件
        Page<CourseBase> courseBasePage = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        //查询数据
        Page<CourseBase> pageResult = courseBaseMapper.selectPage(courseBasePage, courseBaseQueryWrapper);
        //构造返回数据
        long total = pageResult.getTotal();
        List<CourseBase> courseBaseList = pageResult.getRecords();
        return new PageResult<>(courseBaseList, total, pageParams.getPageNo(), pageParams.getPageSize());
    }

    /**
     * 新增课程业务
     * @param companyId  培训机构Id
     * @param dto  新增课程属性
     * @return CourseBaseInfoDto
     */
    @Override
    @Transactional
    public CourseBaseInfoDto addCourse(Long companyId, AddCourseDto dto) {
        //对数据进行封装
        //课程基本信息
        CourseBase courseBase = new CourseBase();
        BeanUtils.copyProperties(dto, courseBase);
        //设置审核状态
        courseBase.setAuditStatus("202002");
        //设置发布状态
        courseBase.setStatus("203001");
        //机构id
        courseBase.setCompanyId(companyId);
        //添加时间
        courseBase.setCreateDate(LocalDateTime.now());
        //向课程基本信息表中插入数据
        int insert = courseBaseMapper.insert(courseBase);
        Long courseId = courseBase.getId();
        //课程营销信息
        //先根据课程id查询营销信息
        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(dto, courseMarket);
        courseMarket.setId(courseId);
        //课程营销校验并保存
        int insert1 = saveCourseMarket(courseMarket);

        if (insert <= 0 || insert1 <= 0) {
            throw new bkSchoolException("业务异常，课程相关信息添加失败,请检查要添加的内容或联系管理员");
        }
        //添加成功
        //返回添加的课程信息
        return queryCourseInfoById(courseId);
    }

    /**
     * 根据课程Id查询课程相关信息
     * @param courseId 课程Id
     * @return CourseBaseInfoDto
     */
    public CourseBaseInfoDto queryCourseInfoById(long courseId) {
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        if (courseBase == null) {
            throw new bkSchoolException("业务异常,查询课程基本信息失败，请检查参数");
        }
        if (courseMarket == null) {
            courseMarket = new CourseMarket();
            courseMarket.setId(courseId);
        }
        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        BeanUtils.copyProperties(courseBase, courseBaseInfoDto);
        BeanUtils.copyProperties(courseMarket, courseBaseInfoDto);
        //查询分类名称
        CourseCategory courseCategoryBySt = courseCategoryMapper.selectById(courseBase.getSt());
        courseBaseInfoDto.setStName(courseCategoryBySt.getName());
        CourseCategory courseCategoryByMt = courseCategoryMapper.selectById(courseBase.getMt());
        courseBaseInfoDto.setMtName(courseCategoryByMt.getName());
        return courseBaseInfoDto;
    }

    /**
     * 更新课程相关信息
     * @param companyId 培训机构Id
     * @param dto 新增课程属性
     * @return CourseBaseInfoDto
     */
    @Override
    @Transactional
    public CourseBaseInfoDto updateCourse(Long companyId, EditCourseDto dto) {
        //课程id
        Long courseId = dto.getId();
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        //非空校验
        if (courseBase == null) {
            throw new bkSchoolException("业务异常，未找到要修改的数据，请重试或联系管理员");
        }
        //业务规则校验，本机构只允许修改本机构的课程
        if (!companyId.equals(courseBase.getCompanyId())) {
            throw new bkSchoolException("业务异常,监测到你正在操作非你名下的课程，请勿危险操作");
        }
        //封装课程基本信息表
        BeanUtils.copyProperties(dto, courseBase);
        //更新
        courseBase.setChangeDate(LocalDateTime.now());
        int courseBaseSaveResultCount = courseBaseMapper.updateById(courseBase);
        if (courseBaseSaveResultCount <= 0) {
            throw new bkSchoolException("业务异常，课程基本信息表更新失败,请检查要更新的内容或联系管理员");
        }
        //创建一个新的营销信息对象
        CourseMarket courseMarket = new CourseMarket();
        //将dto中的课程营销信息拷贝至courseMarket对象中
        BeanUtils.copyProperties(dto, courseMarket);
        //课程营销校验并保存
        int courseMarketSaveResultCount = saveCourseMarket(courseMarket);
        if (courseMarketSaveResultCount <= 0) {
            throw new bkSchoolException("业务异常，课程营销信息表更新失败,请检查要更新的内容或联系管理员");
        }
        return queryCourseInfoById(courseId);
    }

    /**
     * @description 抽取课程营销校验及保存功能
     * @param courseMarket 课程营销信息
     * @return int
     * @author xiaoxu
     * @date 2023/1/17 21:50
     */
    private int saveCourseMarket(CourseMarket courseMarket){
        //判断是否收费
        String charge = courseMarket.getCharge();
        if (StringUtils.isBlank(charge)){
            throw new bkSchoolException("业务异常，请填写收费规则");
        }
        if (charge.equals("201001")) {
            Float price = courseMarket.getPrice();
            if (price == null || price <= 0) {
                throw new bkSchoolException("课程设置了收费价格不能为空且必须大于0");
            }
        }
        //判断营销信息是否填写
        if (courseMarket.getValidDays() == null){
            throw new bkSchoolException("业务异常，请填写有效期");
        }
        //保存课程营销信息，没有则添加，有则更新
        //查询营销信息
        return courseMarketMapper.selectById(courseMarket.getId()) == null ? courseMarketMapper.insert(courseMarket) : courseMarketMapper.updateById(courseMarket);
    }

}
